package com.zhike.service.serviceimpl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.enterprise.inject.New;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.zhike.mapper.UserMapper;
import com.zhike.model.ClockRecord;
import com.zhike.model.One;
import com.zhike.model.One.Two;
import com.zhike.model.One.Two.Three;
import com.zhike.model.One.Two.Three.Four;
import com.zhike.model.Users;
import com.zhike.service.UserService;
import com.zhike.util.BasicsUtil;
import com.zhike.util.DataSourceEnum;
import com.zhike.util.DataSourceHolder;
import com.zhike.util.DateUtil;
import com.zhike.util.JsonUtil;



@Service
public class UserServiceImpl implements UserService{

	@Resource
	UserMapper userMapper;

	/**
	 * 用户登陆接口
	 */
	@Override
	public String login(Users users) {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		
		JsonUtil js = new JsonUtil();
		//返回user对象
		Users login =	userMapper.login(users);
		Users zUsers = userMapper.zkLogin(users);
		if (login==null && zUsers==null) {
			return JsonUtil.blank(false, 400, "此账号不存在");
		}else {

			//如果是绩效系统
			if (login != null) {
				//通过id获取用户详情
				users.setId(login.getId());
				Users users2 = userMapper.getDetailUser(users);
				//拿到登陆对象加密后的密码,转换为小写
				String id = login.getId();
				String md5 = BasicsUtil.getMD5(id.toLowerCase()+users.getPassWord());
				//get user对象的登陆密码是否与用户输入密码匹配
				String password = login.getPassWord();
				//如果匹配 登陆成功 返回用户uid  
				if (md5.equals(password)) {
					//把id去掉"-" 设置别名 方便推送
					login.setAlias(id.replaceAll("-", ""));
					login.setIdentifyLabel("JX");
					login.setId(users2.getId());
					login.setAccount_ID(users2.getAccount_ID());
					login.setName(users2.getName());
					login.setAccount_Name(users2.getName());
					login.setTime(DateUtil.getCurrentTime());
//					userMapper.insertUseRecord(login);
					js.add(login);
					js.setMsg("登陆成功");
					if (users2.getAccount_ID()==null) {
						return JsonUtil.blank(true, 400, "实验室管理系统账号缺失");
					}
					return js.getJson();
				}
				
			}
			
			if (zUsers!=null) {
				users.setId(zUsers.getAccount_ID());
				Users users2 = userMapper.getDetailUser(users);
				
				//拿到登陆对象加密后的密码,转换为小写
				String id = zUsers.getAccount_ID();
				zUsers.setId(id);
				String md5 = BasicsUtil.getMD5(id.toLowerCase()+users.getPassWord());
				String md52 = BasicsUtil.getMD5(md5);
				//user对象的登陆密码是否与用户输入密码匹配
				String password = zUsers.getAccount_Password();
				//如果匹配 登陆成功 返回用户uid  
				if (md52.equals(password)) {
					//把id去掉"-" 设置别名 方便推送
					zUsers.setAlias(id.replaceAll("-", ""));
					zUsers.setIdentifyLabel("SY");
					zUsers.setId(users2.getId());
					zUsers.setAccount_ID(users2.getAccount_ID());
					zUsers.setName(users2.getAccount_Name());
					zUsers.setTime(DateUtil.getCurrentTime());
					zUsers.setAccount_Name(users2.getName());
					js.add(zUsers);
					js.setMsg("登陆成功");
//					userMapper.insertUseRecord(zUsers);
					return js.getJson();
				}else {
					//如果不匹配 登陆失败 返回失败的json
					
					return JsonUtil.blank(false, 400, "密码错误");
				}
			}
		}
		return js.getJson();	
	}

	@Override
	public String membersList(Users users) {
//		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
//		//先查出所有的部门
//		List<Department> departmentList = new ArrayList<Department>();
//		departmentList = userMapper.departmentList();
//	
//	
//		
//		JsonUtil js = new JsonUtil();
//		List<Users> membersList = new ArrayList<Users>();
//		//查询所有人员信息存入list
//		for (int i = 0; i < departmentList.size(); i++) {
//			Department department = departmentList.get(i);
//			membersList  = userMapper.membersList(i+1);
//			department.setuList(membersList);
//		}
//		js.setList(departmentList);
//		return js.getJson();
		DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());

		//第一次传来0000 查出所有公司的id
		List<Users> selectOrganizes1 = userMapper.selectOrganizes("00000000-0000-0000-0000-000000000000");
		Users u = selectOrganizes1.get(0);
		One one = new One();
		one.setName(u.getName());
		one.setID(u.getID());
		one.setAccount(u.getAccount());
		//查出所有部门的list
		List<Users> selectOrganizes = userMapper.selectOrganizes(u.getID());
		
		List<Two> twoList = new ArrayList<Two>();
		for (int i = 0; i < selectOrganizes.size(); i++) {
			Users users3 = selectOrganizes.get(i);
			Two two = new One.Two();
			two.setName(users3.getName());;
			two.setID(users3.getID());
			two.setAccount(users3.getAccount());
			twoList.add(two);
			//第三层 
			List<Users> selectOrganizes2 = userMapper.selectOrganizes(users3.getID());
			List<Users> selectOrganizes3 = userMapper.selectOrganize(users3.getID());
			selectOrganizes2.addAll(selectOrganizes3);
			if (selectOrganizes2.size()<=0) {
				continue;
			}
			List<Three> threeList = new ArrayList<Three>();
			for (int j = 0; j < selectOrganizes2.size(); j++) {
				Users users4 = selectOrganizes2.get(j);
				Three three = new One.Two.Three();
				three.setID(users4.getID());
				three.setName(users4.getName());
				three.setAccount(users4.getAccount());
				threeList.add(three);
				
				//第4层 
				List<Users> selectOrganizes4 = userMapper.selectOrganize(users4.getID());
				if (selectOrganizes4.size()<=0) {
					continue;
				}
				List<Four> fourList = new ArrayList<Four>();
				for (int k = 0; k < selectOrganizes4.size(); k++) {
					Four four = new One.Two.Three.Four();
					Users users5 = selectOrganizes4.get(k);
					four.setID(users5.getID());
					four.setName(users5.getName());
					fourList.add(four);
					threeList.get(j).setChildrens(fourList);
				}
				twoList.get(i).setChildrens(threeList);
			}
			one.setChildrens(twoList);
			
		}
		//把所有部门存进去
		
	
		
		

		//		if (selectOrganizes1!=null) {
//			for (int i = 0; i < selectOrganizes1.size(); i++) {
//				Users users2 = selectOrganizes1.get(i);
//				////这一次ID的部门
//				System.out.println("users2.getID()============"+users2.getID());
//				List<Users> selectOrganizes3 = userMapper.selectOrganizes(users2.getID());
//				//查出人员
//				
//					
//				
//			}
//		}
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add(one);
		return jsonUtil.getJson();
		
	}
	/**
	 * 递归调用 人员列表
	 */
//	public static  List<Users> UsersList(String parentId){
//		DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
//				List<Users> arrayList = new ArrayList<Users>();
//				//先查出第一层公司
//				System.out.println("parentId==================="+parentId);
//				arrayList =userMapper.selectOrganizes(parentId);
//				if (arrayList!=null) {
//					for (int i = 0; i < arrayList.size(); i++) {
//						List<Users> usersList =UserServiceImpl.UsersList(arrayList.get(i).getID());
//						arrayList.get(i).setChildrens(usersList);
//					}
//				}else {
//					return new ArrayList<Users>();
//				}
//				
//				return arrayList;
//		
//	}
	/**
	 * 人员考勤打卡
	 * @throws ParseException      
	 */
	@Override
	public String clock(ClockRecord clockRecord) throws ParseException {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		if (clockRecord.getUid()==null) {
			return JsonUtil.blank(false, 400, "uid不能为空");
		}
		if (clockRecord.getClockAddress()==null) {
			return JsonUtil.blank(false, 400, "打卡地址不能为空");
		}
		if (clockRecord.getLongitude()==null) {
			return JsonUtil.blank(false, 400, "经度不能为空");
		}
		if (clockRecord.getLatitude()==null) {
			return JsonUtil.blank(false, 400, "纬度不能为空");
		}
		//设置用户id
		clockRecord.setUid(clockRecord.getUid().toLowerCase());
		//设置打卡时间
		clockRecord.setTime(DateUtil.getCurrentTimeThree());
		clockRecord.setClockDate(DateUtil.getCurrentTimeTwo());
		//查询上班时间下班时间 经纬度
		List<ClockRecord> arrayList = new ArrayList<ClockRecord>();
		arrayList =userMapper.workOutTime(clockRecord);
	
			
			ClockRecord c = arrayList.get(0);
			
			//规定的打卡的纬度
			String latitude = c.getLatitude();
			//规定的打卡的经度
			String longitude = c.getLongitude();
			
			
			//上班时间和下班时间
			String businessHours = c.getBusinessHours();
			String closingTime = c.getClosingTime();
		
			if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), "12:00:00")) {
			clockRecord.setClockWay("上班打卡");
			ClockRecord s = userMapper.countBusinessClock(clockRecord);
			if (s.getCount()==1) {
				return JsonUtil.blank(false, 400, "已打上班卡");
			}
			}else {
				//下班打卡次数
				clockRecord.setClockWay("下班打卡");
				ClockRecord x = userMapper.countClosingClock(clockRecord);
				if (x.getCount()==1) {
					return JsonUtil.blank(false, 400, "已打下班卡");
				}
				
			}
			
			
			//设置打卡状态
			if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), "12:00:00")) {
				clockRecord.setClockWay("上班打卡");
				if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), businessHours)) {
					clockRecord.setClockStates("正常打卡");
				}else {
					clockRecord.setClockStates("迟到打卡");
				}
			}else {
				clockRecord.setClockWay("下班打卡");
				if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), closingTime)) {
					clockRecord.setClockStates("早退打卡");
				}else {
					clockRecord.setClockStates("正常打卡");
				}
			}
			
			if (BasicsUtil.distance100M(latitude, longitude, clockRecord.getLatitude(), clockRecord.getLongitude())||clockRecord.getClockWifi()==c.getWifiMac()) {
				userMapper.clock(clockRecord);
				return JsonUtil.blank(true, 200, "打卡成功");	
			}else {
				ClockRecord c1 = arrayList.get(1);
				
				//规定的打卡的纬度
				String latitude1 = c1.getLatitude();
				//规定的打卡的经度
				String longitude1 = c1.getLongitude();
				
				
				//上班时间和下班时间
				String businessHours1 = c1.getBusinessHours();
				String closingTime1 = c1.getClosingTime();
			
				if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), "12:00:00")) {
				clockRecord.setClockWay("上班打卡");
				ClockRecord s = userMapper.countBusinessClock(clockRecord);
				if (s.getCount()==1) {
					return JsonUtil.blank(false, 400, "已打上班卡");
				}
				}else {
					//下班打卡次数
					clockRecord.setClockWay("下班打卡");
					ClockRecord x = userMapper.countClosingClock(clockRecord);
					if (x.getCount()==1) {
						return JsonUtil.blank(false, 400, "已打下班卡");
					}
					
				}
				
				
				//设置打卡状态
				if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), "12:00:00")) {
					clockRecord.setClockWay("上班打卡");
					if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), businessHours1)) {
						clockRecord.setClockStates("正常打卡");
					}else {
						clockRecord.setClockStates("迟到打卡");
					}
				}else {
					clockRecord.setClockWay("下班打卡");
					if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), closingTime1)) {
						clockRecord.setClockStates("早退打卡");
					}else {
						clockRecord.setClockStates("正常打卡");
					}
				}
				
				if (BasicsUtil.distance100M(latitude1, longitude1, clockRecord.getLatitude(), clockRecord.getLongitude())||clockRecord.getClockWifi()==c.getWifiMac()) {
					userMapper.clock(clockRecord);
					return JsonUtil.blank(true, 200, "打卡成功");	
				}else {
					return JsonUtil.blank(false, 400, "不在打卡范围内");
				}
				
			}
		}
		
		
	

	/**
	 * 查询今天打卡状态
	 * @throws ParseException 
	 */
	@Override
	public String clockSelect(ClockRecord clockRecord) throws ParseException {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		clockRecord.setUid(clockRecord.getUid().toLowerCase());
		clockRecord.setClockDate(DateUtil.getCurrentTimeTwo());
		JsonUtil jsonUtil = new JsonUtil();
		Map<String, Object> map = new HashMap<>();
		ClockRecord cr = userMapper.clockSelect(clockRecord);
		//如果打卡时间小于十二点 显示上班打卡
		if (DateUtil.dateCompare(DateUtil.getCurrentTimeThree(), "12:00:00")) {
			map.put("states", "上班打卡");
		}else {
			map.put("states", "下班打卡");
		}
		//上班打卡次数
		clockRecord.setClockWay("上班打卡");
		ClockRecord s = userMapper.countBusinessClock(clockRecord);
		if (s.getCount()==0) {
			map.put("clockIn", false);
		}else {
			map.put("clockIn", true);
		}
		//下班打卡次数
		clockRecord.setClockWay("下班打卡");
		ClockRecord x = userMapper.countClosingClock(clockRecord);
		if (x.getCount()==0) {
			map.put("clockOut", false);
		}else {
			map.put("clockOut", true);
		}
		jsonUtil.add(map);
		return jsonUtil.getJson();
	}

	@Override
	public String selectClockList(ClockRecord clockRecord) {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		List<ClockRecord> list = new ArrayList<>();
		JsonUtil jsonUtil = new JsonUtil();
		clockRecord.setUid(clockRecord.getUid().toLowerCase());
		list = userMapper.selectClockList(clockRecord);
		jsonUtil.setList(list);
		return jsonUtil.getJson();
	}

	@Override
	public String ClockDay(ClockRecord clockRecord) {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		//几个人迟到
		Integer countLate =	userMapper.countLate(clockRecord);
		clockRecord.setLateCount(countLate);
		//几个人早退
		Integer countLeaveEarly =	userMapper.countLeaveEarly(clockRecord);
		clockRecord.setLeaveEarlyCount(countLeaveEarly);
		//几个人没打上班卡 查询公司总人数  查询上班打卡人数   总人数 - 上班打卡人数 =没打卡人数
		Integer integer = userMapper.countUser();
		Integer countWorkIn =	userMapper.countWorkIn(clockRecord);
		clockRecord.setLackOfCardIn(integer-countWorkIn);
		//几个人没打下班卡 查询下班打卡人数  总人数 - 下班打卡人数 =没打卡人数
		Integer countWorkOut =	userMapper.countWorkOut(clockRecord);
		clockRecord.setLackOfCardOut(integer-countWorkOut);
		//几个人全天没打卡 查询今天有几个打过卡  去重复 uid  总人数 减去打过卡的人数 =没打卡人数
		Integer countClock = userMapper.countClock(clockRecord);
		clockRecord.setAbsenteeism(integer-countClock);
		JsonUtil js = new JsonUtil();
		js.add(clockRecord);
		return js.getJson();
	}

	@Override
	public String ClockMonth(ClockRecord clockRecord) {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		//clockRecord只有1个属性 时间 
		//查出所有人的uid  存进list 
		JsonUtil jsonUtil = new JsonUtil();
		List<Users> userList = new ArrayList<>();
		List<ClockRecord> clockRecordList = new ArrayList<>();
		userList = userMapper.uidAll(clockRecord);
		for (int i = 0; i < userList.size(); i++) {
			
			//早退次数  根据uid 查询 早退次数 
			ClockRecord clockRecord2 = new ClockRecord();
			clockRecord2.setUid(userList.get(i).getId());
			clockRecord2.setName(userList.get(i).getName());
			clockRecord2.setClockDate(clockRecord.getClockDate());
			
			//多了两个属性 uid 和名字
			
			Integer leaveEarlyCount = userMapper.selectLeaveEarlyCount(clockRecord);
			clockRecord2.setLeaveEarlyCount(leaveEarlyCount);
			
			
			//迟到几次  根据uid 查询 迟到次数 
			Integer lateCount	= userMapper.selectLateCount(clockRecord);
			clockRecord2.setLateCount(lateCount);
			
			//查询这个月有多少天 
			int year = Integer.parseInt(clockRecord.getClockDate().substring(0, 4));
			int month = Integer.parseInt(clockRecord.getClockDate().substring(5, 7));
			int days = DateUtil.getDays(year, month);
			
			//缺上班卡次数
			//查询这个uid 几次上班打卡
			//查询这个月有多少天  -  这个月这个id打了多少次上班卡卡 =缺上班卡
			Integer workInCount =	userMapper.selectWorkInClock(clockRecord);
			clockRecord2.setLackOfCardIn(days-workInCount);
			
			//缺上班卡次数
			//查询这个uid 几次下班打卡
			//查询这个月有多少天  -  这个月这个id打了多少次下班卡卡 =缺下班卡
			Integer workOutCount = userMapper.selectWorkOutClock(clockRecord);
			clockRecord2.setLackOfCardOut(workOutCount);
			
			//旷班次数
			int countAbsenteeism=0;
			
			for (int j = 1; j <= days; j++) {
				//当前日期
				
				clockRecord.setClockDate(clockRecord.getClockDate().substring(0, 7));
				clockRecord.setClockDate(clockRecord.getClockDate()+"-"+BasicsUtil.stringFormatUtil(j));
				Integer cInteger = userMapper.selectCountAbsenteeism(clockRecord);
				if (cInteger==0) {
					countAbsenteeism++;
				}
			}
			clockRecord2.setAbsenteeism(countAbsenteeism);
			clockRecordList.add(clockRecord2);
		}
		jsonUtil.setList(clockRecordList);
		return jsonUtil.getJson();
	}
	/**
	 * 签到明细
	 */
	@Override
	public String signInDetail(ClockRecord clockRecord) {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		List<ClockRecord> list = new ArrayList<>();
		JsonUtil js = new JsonUtil();
		list = userMapper.signInDetail(clockRecord);
		js.setList(list);
		return js.getJson();
	}
	/**
	 * 用户当天的五种状态的签到记录
	 */
	@Override
	public String clockListToday(ClockRecord clockRecord) {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		//查出所有人的uid  存进list 
		JsonUtil jsonUtil = new JsonUtil();
		List<Users> userList = new ArrayList<>();
		List<ClockRecord> clockRecordList = new ArrayList<>();
		userList = userMapper.selectUserTitle();
		if (clockRecord.getClockStates().equals("迟到打卡")) {
			for (int i = 0; i < userList.size(); i++) {
				Users users = userList.get(i);
				clockRecord.setUid(users.getId().toLowerCase());
				ClockRecord c2 = userMapper.getStates1(clockRecord);
				if (c2!=null) {
					c2.settName(userList.get(i).gettName());
					clockRecordList.add(c2);
				}
				jsonUtil.setList(clockRecordList);
			}
		}
		if (clockRecord.getClockStates().equals("早退打卡")) {
			for (int i = 0; i < userList.size(); i++) {
				clockRecord.setUid(userList.get(i).getId());
				ClockRecord c2 = userMapper.getStates1(clockRecord);
				if (c2!=null) {
					c2.settName(userList.get(i).gettName());
					clockRecordList.add(c2);
				}
				jsonUtil.setList(clockRecordList);
			}
		}
		if (clockRecord.getClockStates().equals("缺上班卡")) {
			for (int i = 0; i < userList.size(); i++) {
				clockRecord.setUid(userList.get(i).getId());
				ClockRecord newCr = new ClockRecord();
				//今天打上班卡了吗
				clockRecord.setClockWay("上班打卡");
				Integer count = userMapper.isWorkIn(clockRecord);
				//如果没打  加入list  名字 职称 uid
				if (count==0) {
					newCr.setUid(userList.get(i).getId());
					newCr.setName(userList.get(i).getName());
					newCr.settName(userList.get(i).gettName());
					clockRecordList.add(newCr);
				}
			}
			jsonUtil.setList(clockRecordList);
		}
		if (clockRecord.getClockStates().equals("缺下班卡")) {
			for (int i = 0; i < userList.size(); i++) {
				clockRecord.setUid(userList.get(i).getId());
				ClockRecord newCr = new ClockRecord();
				//今天打下班卡了吗
				clockRecord.setClockWay("下班打卡");
				Integer count = userMapper.isWorkIn(clockRecord);
				//如果没打  加入list  名字 职称 uid
				if (count==0) {
					newCr.setUid(userList.get(i).getId());
					newCr.setName(userList.get(i).getName());
					newCr.settName(userList.get(i).gettName());
					clockRecordList.add(newCr);
				}
			}
			jsonUtil.setList(clockRecordList);
		}
		if (clockRecord.getClockStates().equals("缺全天卡")) {
			for (int i = 0; i < userList.size(); i++) {
				clockRecord.setUid(userList.get(i).getId());
				ClockRecord newCr = new ClockRecord();
				//今天打下班卡了吗
				clockRecord.setClockWay("上班打卡");
				Integer count = userMapper.isWorkIn(clockRecord);
				//今天打下班卡了吗
				clockRecord.setClockWay("下班打卡");
				Integer countOut = userMapper.isWorkIn(clockRecord);
				//如果没打  加入list  名字 职称 uid
				if (count==0 && countOut==0) {
					newCr.setUid(userList.get(i).getId());
					newCr.setName(userList.get(i).getName());
					newCr.settName(userList.get(i).gettName());
					clockRecordList.add(newCr);
				}
			}
			jsonUtil.setList(clockRecordList);
		}
		
		return jsonUtil.getJson();
	}
	/**
	 * 每个人这个月的打卡日期记录
	 */
	@Override
	public String dateRecord(ClockRecord clockRecord) {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		clockRecord.setUid(clockRecord.getUid().toLowerCase());
		JsonUtil js = new JsonUtil();
		List<ClockRecord> list = new ArrayList<>();
		list = userMapper.dateRecord(clockRecord);
		js.setList(list);
		return js.getJson();
	}

	@Override
	public String usersBinding(Users users) {
		DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
		//绑定数据
		Gson gson = new Gson();
		Users fromJson = gson.fromJson(users.getData(), Users.class);
		fromJson.setAccount_ID(fromJson.getAccount_ID().toUpperCase());
		userMapper.updateBinding(fromJson);
		return JsonUtil.blank(true, 200, "接口调用成功");
	}
	
	
}
